package com.joker.demo.admin.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joker.demo.admin.domain.dto.ThreadPoolMonitorQueryDTO;
import com.joker.demo.admin.domain.dto.ExecutorStatisticsQueryDTO;
import com.joker.demo.admin.domain.po.ThreadPoolMonitorPO;
import com.joker.demo.admin.domain.vo.PageResult;
import com.joker.demo.admin.domain.vo.ExecutorStatisticsVO;
import com.joker.demo.admin.domain.vo.OverallStatistics;
import com.joker.demo.admin.domain.vo.ExecutorStatusStatistics;
import com.joker.demo.admin.domain.vo.TaskExecutionStatistics;
import com.joker.demo.admin.domain.vo.HourlyStatisticsVO;
import com.joker.demo.admin.domain.vo.AppStatisticsVO;
import com.joker.demo.admin.mapper.ThreadPoolMonitorMapper;
import com.joker.demo.admin.service.ThreadPoolMonitorService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 线程池监控Service实现类
 *
 * @author : feixiang.li
 * @since : 2025-01-27 10:00
 */
@Slf4j
@Service
public class ThreadPoolMonitorServiceImpl implements ThreadPoolMonitorService {

    @Resource
    private ThreadPoolMonitorMapper threadPoolMonitorMapper;

    @Override
    public void saveMonitorData(ThreadPoolMonitorPO monitorData) {
        try {
            threadPoolMonitorMapper.insert(monitorData);
            log.info("保存线程池监控数据成功: {}", monitorData.getRegisterKey());
        } catch (Exception e) {
            log.error("保存线程池监控数据失败: {}", monitorData.getRegisterKey(), e);
        }
    }

    @Override
    public PageResult<ThreadPoolMonitorPO> queryMonitorData(ThreadPoolMonitorQueryDTO queryDTO) {
        try {
            // 构建查询条件
            LambdaQueryWrapper<ThreadPoolMonitorPO> queryWrapper = new LambdaQueryWrapper<>();
            
            if (queryDTO.getRegisterKey() != null && !queryDTO.getRegisterKey().trim().isEmpty()) {
                queryWrapper.eq(ThreadPoolMonitorPO::getRegisterKey, queryDTO.getRegisterKey());
            }
            
           if (queryDTO.getAppName() != null && !queryDTO.getAppName().trim().isEmpty()) {
                queryWrapper.eq(ThreadPoolMonitorPO::getAppName, queryDTO.getAppName());
            }
            
            if (queryDTO.getStartTime() != null) {
                queryWrapper.ge(ThreadPoolMonitorPO::getMonitorTime, queryDTO.getStartTime());
            }
            
            if (queryDTO.getEndTime() != null) {
                queryWrapper.le(ThreadPoolMonitorPO::getMonitorTime, queryDTO.getEndTime());
            }
            
            // 按监控时间倒序排列
            queryWrapper.orderByDesc(ThreadPoolMonitorPO::getMonitorTime);
            
            // 分页查询
            Page<ThreadPoolMonitorPO> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
            IPage<ThreadPoolMonitorPO> result = threadPoolMonitorMapper.selectPage(page, queryWrapper);
            
            // 构建分页结果
            PageResult<ThreadPoolMonitorPO> pageResult = PageResult.of(
                result.getRecords(), 
                result.getTotal(), 
                Long.valueOf(queryDTO.getPageNum()), 
                Long.valueOf(queryDTO.getPageSize())
            );
            
            return pageResult;
        } catch (Exception e) {
            log.error("查询线程池监控数据失败", e);
            return new PageResult<>();
        }
    }

    @Override
    public List<ThreadPoolMonitorPO> queryLatestMonitorData(String registerKey, Integer limit) {
        try {
            if (limit == null || limit <= 0) {
                limit = 10;
            }
            return threadPoolMonitorMapper.queryLatestMonitorData(registerKey, limit);
        } catch (Exception e) {
            log.error("查询最新监控数据失败: {}", registerKey, e);
            return Collections.emptyList();
        }
    }

    @Override
    public List<ThreadPoolMonitorPO> queryAllLatestMonitorData() {
        try {
            return threadPoolMonitorMapper.queryAllLatestMonitorData();
        } catch (Exception e) {
            log.error("查询所有最新监控数据失败", e);
            return Collections.emptyList();
        }
    }

    @Override
    public List<ThreadPoolMonitorPO> query24HourSummaryData() {
        try {
            // 计算24小时前的时间
            LocalDateTime startTime = LocalDateTime.now().minusHours(24);
            return threadPoolMonitorMapper.query24HourSummaryData(startTime);
        } catch (Exception e) {
            log.error("查询24小时汇总监控数据失败", e);
            return Collections.emptyList();
        }
    }

    @Override
    public ThreadPoolMonitorPO query24HourSummaryDataByRegisterKey(String registerKey) {
        try {
            if (registerKey == null || registerKey.trim().isEmpty()) {
                log.warn("执行器标识为空");
                return null;
            }
            // 计算24小时前的时间
            LocalDateTime startTime = LocalDateTime.now().minusHours(24);
            return threadPoolMonitorMapper.query24HourSummaryDataByRegisterKey(registerKey, startTime);
        } catch (Exception e) {
            log.error("查询执行器24小时汇总监控数据失败: {}", registerKey, e);
            return null;
        }
    }

    @Override
    public ThreadPoolMonitorPO queryMonitorStatistics(String registerKey, String startTime, String endTime) {
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime start = LocalDateTime.parse(startTime, formatter);
            LocalDateTime end = LocalDateTime.parse(endTime, formatter);
            
            return threadPoolMonitorMapper.queryMonitorStatistics(registerKey, start, end);
        } catch (Exception e) {
            log.error("查询监控统计信息失败: {}", registerKey, e);
            return null;
        }
    }

    @Override
    public void cleanHistoryData(Integer days) {
        try {
            LocalDateTime cutoffTime = LocalDateTime.now().minusDays(days);
            
            LambdaQueryWrapper<ThreadPoolMonitorPO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.lt(ThreadPoolMonitorPO::getMonitorTime, cutoffTime);
            
            int deletedCount = threadPoolMonitorMapper.delete(queryWrapper);
            log.info("清理历史监控数据完成，删除 {} 条记录", deletedCount);
        } catch (Exception e) {
            log.error("清理历史监控数据失败", e);
        }
    }

    @Override
    public ExecutorStatisticsVO queryExecutorStatistics(ExecutorStatisticsQueryDTO queryDTO) {
        if (Objects.isNull(queryDTO) || Objects.isNull(queryDTO.getQueryDate())) {
            return null;
        }

        try {
            // 解析查询日期
            Date queryDate = DateUtil.parseDate(queryDTO.getQueryDate());
            Date startTime = DateUtil.beginOfDay(queryDate);
            Date endTime = DateUtil.endOfDay(queryDate);
            
            LocalDateTime startDateTime = startTime.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime();
            LocalDateTime endDateTime = endTime.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime();

            // 构建查询条件
            LambdaQueryWrapper<ThreadPoolMonitorPO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.ge(ThreadPoolMonitorPO::getMonitorTime, startDateTime);
            queryWrapper.le(ThreadPoolMonitorPO::getMonitorTime, endDateTime);

            // 添加可选过滤条件
            if (Objects.nonNull(queryDTO.getAppName()) && !queryDTO.getAppName().trim().isEmpty()) {
                queryWrapper.eq(ThreadPoolMonitorPO::getAppName, queryDTO.getAppName());
            }
            if (Objects.nonNull(queryDTO.getRegisterKey()) && !queryDTO.getRegisterKey().trim().isEmpty()) {
                queryWrapper.eq(ThreadPoolMonitorPO::getRegisterKey, queryDTO.getRegisterKey());
            }

            // 按监控时间升序排序
            queryWrapper.orderByAsc(ThreadPoolMonitorPO::getMonitorTime);

            // 查询所有符合条件的监控数据
            List<ThreadPoolMonitorPO> monitorDataList = threadPoolMonitorMapper.selectList(queryWrapper);

            // 构建返回结果
            ExecutorStatisticsVO result = new ExecutorStatisticsVO();
            result.setQueryDate(queryDTO.getQueryDate());

            // 计算总体统计信息
            OverallStatistics overallStats = calculateOverallStatistics(monitorDataList);
            result.setOverallStatistics(overallStats);

            // 计算执行器状态统计
            ExecutorStatusStatistics statusStats = calculateExecutorStatusStatistics(monitorDataList);
            result.setExecutorStatusStatistics(statusStats);

            // 计算任务执行统计
            TaskExecutionStatistics taskStats = calculateTaskExecutionStatistics(monitorDataList);
            result.setTaskExecutionStatistics(taskStats);

            // 构建执行器基本信息列表（简化版，避免套娃）
            List<ExecutorStatisticsVO.ExecutorBasicInfo> executorBasicInfos = buildExecutorBasicInfos(monitorDataList);
            result.setExecutorBasicInfos(executorBasicInfos);

            // 构建小时统计信息
            List<HourlyStatisticsVO> hourlyStats = buildHourlyStatistics(monitorDataList);
            result.setHourlyStatistics(hourlyStats);

            // 构建应用统计信息
            List<AppStatisticsVO> appStats = buildAppStatistics(monitorDataList);
            result.setAppStatistics(appStats);

            return result;

        } catch (Exception e) {
            log.error("查询执行器统计信息失败，queryDate: {}", queryDTO.getQueryDate(), e);
            return null;
        }
    }

    /**
     * 计算总体统计信息
     */
    private OverallStatistics calculateOverallStatistics(List<ThreadPoolMonitorPO> monitorDataList) {
        OverallStatistics stats = new OverallStatistics();

        if (monitorDataList.isEmpty()) {
            stats.setTotalExecutors(0);
            stats.setTotalApps(0);
            stats.setOnlineExecutors(0);
            stats.setOfflineExecutors(0);
            stats.setTotalTasks(0L);
            stats.setTotalActiveThreads(0);
            stats.setTotalRunningTasks(0);
            stats.setAverageMemoryUsage(BigDecimal.ZERO);
            return stats;
        }

        // 获取最新的监控数据（每个执行器的最新记录）
        Map<String, ThreadPoolMonitorPO> latestDataMap = monitorDataList.stream()
                .collect(Collectors.groupingBy(
                        ThreadPoolMonitorPO::getRegisterKey,
                        Collectors.collectingAndThen(
                                Collectors.maxBy(Comparator.comparing(ThreadPoolMonitorPO::getMonitorTime)),
                                opt -> opt.orElse(null)
                        )
                ));

        List<ThreadPoolMonitorPO> latestDataList = latestDataMap.values().stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        // 计算统计信息
        stats.setTotalExecutors(latestDataList.size());
        stats.setTotalApps((int) latestDataList.stream()
                .map(ThreadPoolMonitorPO::getAppName)
                .distinct()
                .count());

        // 判断在线/离线状态（这里简单判断：如果最近5分钟有数据则认为在线）
        LocalDateTime fiveMinutesAgo = LocalDateTime.now().minusMinutes(5);
        long onlineCount = latestDataList.stream()
                .filter(data -> data.getMonitorTime().isAfter(fiveMinutesAgo))
                .count();
        stats.setOnlineExecutors((int) onlineCount);
        stats.setOfflineExecutors((int) (latestDataList.size() - onlineCount));

        // 计算任务和线程统计
        stats.setTotalTasks(latestDataList.stream()
                .mapToLong(data -> data.getTaskCount() != null ? data.getTaskCount() : 0)
                .sum());
        stats.setTotalActiveThreads(latestDataList.stream()
                .mapToInt(data -> data.getActiveCount() != null ? data.getActiveCount() : 0)
                .sum());
        stats.setTotalRunningTasks(latestDataList.stream()
                .mapToInt(data -> data.getRunningTaskCount() != null ? data.getRunningTaskCount() : 0)
                .sum());

        // 计算平均内存使用率
        double avgMemoryUsage = latestDataList.stream()
                .filter(data -> data.getMemoryUsagePercent() != null)
                .mapToDouble(data -> data.getMemoryUsagePercent().doubleValue())
                .average()
                .orElse(0.0);
        stats.setAverageMemoryUsage(BigDecimal.valueOf(avgMemoryUsage));

        return stats;
    }

    /**
     * 计算执行器状态统计
     */
    private ExecutorStatusStatistics calculateExecutorStatusStatistics(List<ThreadPoolMonitorPO> monitorDataList) {
        ExecutorStatusStatistics stats = new ExecutorStatusStatistics();

        if (monitorDataList.isEmpty()) {
            stats.setNormalCount(0);
            stats.setWarningCount(0);
            stats.setErrorCount(0);
            stats.setOfflineCount(0);
            return stats;
        }

        // 获取最新的监控数据
        Map<String, ThreadPoolMonitorPO> latestDataMap = monitorDataList.stream()
                .collect(Collectors.groupingBy(
                        ThreadPoolMonitorPO::getRegisterKey,
                        Collectors.collectingAndThen(
                                Collectors.maxBy(Comparator.comparing(ThreadPoolMonitorPO::getMonitorTime)),
                                opt -> opt.orElse(null)
                        )
                ));

        List<ThreadPoolMonitorPO> latestDataList = latestDataMap.values().stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        LocalDateTime fiveMinutesAgo = LocalDateTime.now().minusMinutes(5);
        int normalCount = 0;
        int warningCount = 0;
        int errorCount = 0;
        int offlineCount = 0;

        for (ThreadPoolMonitorPO data : latestDataList) {
            if (data.getMonitorTime().isBefore(fiveMinutesAgo)) {
                offlineCount++;
            } else {
                // 根据内存使用率和队列使用率判断状态
                boolean isHighMemory = data.getMemoryUsagePercent() != null && 
                        data.getMemoryUsagePercent().compareTo(BigDecimal.valueOf(80)) > 0;
                boolean isHighQueue = data.getQueueSize() != null && data.getQueueRemainingCapacity() != null &&
                        data.getQueueSize() > 0 && 
                        (data.getQueueSize() - data.getQueueRemainingCapacity()) * 100.0 / data.getQueueSize() > 80;

                if (isHighMemory || isHighQueue) {
                    if (data.getMemoryUsagePercent() != null && 
                            data.getMemoryUsagePercent().compareTo(BigDecimal.valueOf(95)) > 0) {
                        errorCount++;
                    } else {
                        warningCount++;
                    }
                } else {
                    normalCount++;
                }
            }
        }

        stats.setNormalCount(normalCount);
        stats.setWarningCount(warningCount);
        stats.setErrorCount(errorCount);
        stats.setOfflineCount(offlineCount);

        return stats;
    }

    /**
     * 计算任务执行统计
     */
    private TaskExecutionStatistics calculateTaskExecutionStatistics(List<ThreadPoolMonitorPO> monitorDataList) {
        TaskExecutionStatistics stats = new TaskExecutionStatistics();

        if (monitorDataList.isEmpty()) {
            stats.setTotalCompletedTasks(0L);
            stats.setTotalFailedTasks(0L);
            stats.setTotalDelayTasks(0L);
            stats.setAverageTaskExecutionTime(BigDecimal.ZERO);
            stats.setTaskSuccessRate(BigDecimal.ZERO);
            return stats;
        }

        // 计算任务统计
        stats.setTotalCompletedTasks(monitorDataList.stream()
                .mapToLong(data -> data.getCompletedTaskCount() != null ? data.getCompletedTaskCount() : 0)
                .sum());
        stats.setTotalFailedTasks(monitorDataList.stream()
                .mapToLong(data -> data.getFailedTasksLastMinute() != null ? data.getFailedTasksLastMinute() : 0)
                .sum());
        stats.setTotalDelayTasks(monitorDataList.stream()
                .mapToLong(data -> data.getDelayTaskCount() != null ? data.getDelayTaskCount() : 0)
                .sum());

        // 计算平均任务执行时间
        double avgExecutionTime = monitorDataList.stream()
                .filter(data -> data.getAverageTaskExecutionTimeMs() != null)
                .mapToDouble(data -> data.getAverageTaskExecutionTimeMs().doubleValue())
                .average()
                .orElse(0.0);
        stats.setAverageTaskExecutionTime(BigDecimal.valueOf(avgExecutionTime));

        // 计算任务成功率
        long totalTasks = stats.getTotalCompletedTasks() + stats.getTotalFailedTasks();
        if (totalTasks > 0) {
            double successRate = (double) stats.getTotalCompletedTasks() / totalTasks * 100;
            stats.setTaskSuccessRate(BigDecimal.valueOf(successRate));
        } else {
            stats.setTaskSuccessRate(BigDecimal.ZERO);
        }

        return stats;
    }

    /**
     * 构建执行器基本信息列表（简化版，避免套娃）
     */
    private List<ExecutorStatisticsVO.ExecutorBasicInfo> buildExecutorBasicInfos(List<ThreadPoolMonitorPO> monitorDataList) {
        if (monitorDataList.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取每个执行器的最新数据
        Map<String, ThreadPoolMonitorPO> latestDataMap = monitorDataList.stream()
                .collect(Collectors.groupingBy(
                        ThreadPoolMonitorPO::getRegisterKey,
                        Collectors.collectingAndThen(
                                Collectors.maxBy(Comparator.comparing(ThreadPoolMonitorPO::getMonitorTime)),
                                opt -> opt.orElse(null)
                        )
                ));

        return latestDataMap.values().stream()
                .filter(Objects::nonNull)
                .map(this::convertToExecutorBasicInfo)
                .collect(Collectors.toList());
    }

    /**
     * 构建执行器基本信息VO
     */
    private ExecutorStatisticsVO.ExecutorBasicInfo convertToExecutorBasicInfo(ThreadPoolMonitorPO monitorData) {
        ExecutorStatisticsVO.ExecutorBasicInfo basicInfo = new ExecutorStatisticsVO.ExecutorBasicInfo();
        basicInfo.setRegisterKey(monitorData.getRegisterKey());
        basicInfo.setAppName(monitorData.getAppName());
        basicInfo.setMonitorTime(monitorData.getMonitorTime());
        basicInfo.setCorePoolSize(monitorData.getCorePoolSize());
        basicInfo.setMaximumPoolSize(monitorData.getMaximumPoolSize());
        basicInfo.setPoolSize(monitorData.getPoolSize());
        basicInfo.setActiveCount(monitorData.getActiveCount());
        basicInfo.setQueueSize(monitorData.getQueueSize());
        basicInfo.setQueueRemainingCapacity(monitorData.getQueueRemainingCapacity());
        basicInfo.setCompletedTaskCount(monitorData.getCompletedTaskCount());
        basicInfo.setTaskCount(monitorData.getTaskCount());
        basicInfo.setRunningTaskCount(monitorData.getRunningTaskCount());
        basicInfo.setDelayTaskCount(monitorData.getDelayTaskCount());
        basicInfo.setCompletedTasksLastMinute(monitorData.getCompletedTasksLastMinute());
        basicInfo.setFailedTasksLastMinute(monitorData.getFailedTasksLastMinute());
        basicInfo.setAverageTaskExecutionTimeMs(monitorData.getAverageTaskExecutionTimeMs());
        basicInfo.setMemoryUsagePercent(monitorData.getMemoryUsagePercent());
        basicInfo.setUsedMemoryMb(monitorData.getUsedMemoryMb());
        basicInfo.setMaxMemoryMb(monitorData.getMaxMemoryMb());
        basicInfo.setLastHeartbeatTime(monitorData.getMonitorTime());

        // 设置执行器状态和健康状态
        LocalDateTime fiveMinutesAgo = LocalDateTime.now().minusMinutes(5);
        if (monitorData.getMonitorTime().isBefore(fiveMinutesAgo)) {
            basicInfo.setStatus("离线");
            basicInfo.setHealthStatus("离线");
        } else {
            boolean isHighMemory = monitorData.getMemoryUsagePercent() != null && 
                    monitorData.getMemoryUsagePercent().compareTo(BigDecimal.valueOf(80)) > 0;
            boolean isHighQueue = monitorData.getQueueSize() != null && monitorData.getQueueRemainingCapacity() != null &&
                    monitorData.getQueueSize() > 0 && 
                    (monitorData.getQueueSize() - monitorData.getQueueRemainingCapacity()) * 100.0 / monitorData.getQueueSize() > 80;

            if (isHighMemory || isHighQueue) {
                if (monitorData.getMemoryUsagePercent() != null && 
                        monitorData.getMemoryUsagePercent().compareTo(BigDecimal.valueOf(95)) > 0) {
                    basicInfo.setStatus("异常");
                    basicInfo.setHealthStatus("异常");
                } else {
                    basicInfo.setStatus("警告");
                    basicInfo.setHealthStatus("警告");
                }
            } else {
                basicInfo.setStatus("正常");
                basicInfo.setHealthStatus("健康");
            }
        }

        return basicInfo;
    }

    /**
     * 构建小时统计信息
     */
    private List<HourlyStatisticsVO> buildHourlyStatistics(List<ThreadPoolMonitorPO> monitorDataList) {
        List<HourlyStatisticsVO> hourlyStats = new ArrayList<>();

        // 初始化24小时的数据
        for (int hour = 0; hour < 24; hour++) {
            HourlyStatisticsVO stats = new HourlyStatisticsVO();
            stats.setHour(hour);
            stats.setExecutorCount(0);
            stats.setTotalTasks(0L);
            stats.setCompletedTasks(0L);
            stats.setFailedTasks(0L);
            stats.setAverageMemoryUsage(BigDecimal.ZERO);
            stats.setAverageActiveThreads(0);
            hourlyStats.add(stats);
        }

        if (monitorDataList.isEmpty()) {
            return hourlyStats;
        }

        // 按小时分组统计
        Map<Integer, List<ThreadPoolMonitorPO>> hourlyDataMap = monitorDataList.stream()
                .collect(Collectors.groupingBy(data -> data.getMonitorTime().getHour()));

        for (Map.Entry<Integer, List<ThreadPoolMonitorPO>> entry : hourlyDataMap.entrySet()) {
            int hour = entry.getKey();
            List<ThreadPoolMonitorPO> hourData = entry.getValue();

            if (hour >= 0 && hour < 24) {
                HourlyStatisticsVO stats = hourlyStats.get(hour);
                
                // 计算该小时的统计信息
                stats.setExecutorCount((int) hourData.stream()
                        .map(ThreadPoolMonitorPO::getRegisterKey)
                        .distinct()
                        .count());
                stats.setTotalTasks(hourData.stream()
                        .mapToLong(data -> data.getTaskCount() != null ? data.getTaskCount() : 0)
                        .sum());
                stats.setCompletedTasks(hourData.stream()
                        .mapToLong(data -> data.getCompletedTaskCount() != null ? data.getCompletedTaskCount() : 0)
                        .sum());
                stats.setFailedTasks(hourData.stream()
                        .mapToLong(data -> data.getFailedTasksLastMinute() != null ? data.getFailedTasksLastMinute() : 0)
                        .sum());

                // 计算平均内存使用率
                double avgMemoryUsage = hourData.stream()
                        .filter(data -> data.getMemoryUsagePercent() != null)
                        .mapToDouble(data -> data.getMemoryUsagePercent().doubleValue())
                        .average()
                        .orElse(0.0);
                stats.setAverageMemoryUsage(BigDecimal.valueOf(avgMemoryUsage));

                // 计算平均活跃线程数
                int avgActiveThreads = (int) hourData.stream()
                        .filter(data -> data.getActiveCount() != null)
                        .mapToInt(ThreadPoolMonitorPO::getActiveCount)
                        .average()
                        .orElse(0.0);
                stats.setAverageActiveThreads(avgActiveThreads);
            }
        }

        return hourlyStats;
    }

    /**
     * 构建应用统计信息
     */
    private List<AppStatisticsVO> buildAppStatistics(List<ThreadPoolMonitorPO> monitorDataList) {
        if (monitorDataList.isEmpty()) {
            return new ArrayList<>();
        }

        // 按应用名称分组
        Map<String, List<ThreadPoolMonitorPO>> appDataMap = monitorDataList.stream()
                .collect(Collectors.groupingBy(ThreadPoolMonitorPO::getAppName));

        return appDataMap.entrySet().stream()
                .map(entry -> {
                    String appName = entry.getKey();
                    List<ThreadPoolMonitorPO> appData = entry.getValue();

                    AppStatisticsVO stats = new AppStatisticsVO();
                    stats.setAppName(appName);
                    stats.setExecutorCount((int) appData.stream()
                            .map(ThreadPoolMonitorPO::getRegisterKey)
                            .distinct()
                            .count());
                    stats.setTotalTasks(appData.stream()
                            .mapToLong(data -> data.getTaskCount() != null ? data.getTaskCount() : 0)
                            .sum());
                    stats.setCompletedTasks(appData.stream()
                            .mapToLong(data -> data.getCompletedTaskCount() != null ? data.getCompletedTaskCount() : 0)
                            .sum());
                    stats.setFailedTasks(appData.stream()
                            .mapToLong(data -> data.getFailedTasksLastMinute() != null ? data.getFailedTasksLastMinute() : 0)
                            .sum());

                    // 计算平均内存使用率
                    double avgMemoryUsage = appData.stream()
                            .filter(data -> data.getMemoryUsagePercent() != null)
                            .mapToDouble(data -> data.getMemoryUsagePercent().doubleValue())
                            .average()
                            .orElse(0.0);
                    stats.setAverageMemoryUsage(BigDecimal.valueOf(avgMemoryUsage));

                    // 计算平均活跃线程数
                    int avgActiveThreads = (int) appData.stream()
                            .filter(data -> data.getActiveCount() != null)
                            .mapToInt(ThreadPoolMonitorPO::getActiveCount)
                            .average()
                            .orElse(0.0);
                    stats.setAverageActiveThreads(avgActiveThreads);

                    return stats;
                })
                .collect(Collectors.toList());
    }
}
